package com.bjfu.intelligentrecognizeserver.handler;

import com.bjfu.intelligentrecognizeserver.common.constant.MessageConstant;
import com.bjfu.intelligentrecognizeserver.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理器，处理项目中抛出的业务异常
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //捕获业务异常
    @ExceptionHandler
    public Result<Object> exceptionHandler(Exception e) {
        if(e instanceof ClientAbortException) {
            //客户端断开连接，无需处理
            //log.warn("Client aborted connection: {}", e.getMessage());
            return null;
        }
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    //处理sql异常
    @ExceptionHandler
    public Result<Object> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String username = message.split(" ")[2];
            String msg = username + MessageConstant.ALREADY_EXIST;
            return Result.error(msg);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}

